package com.company.project.web;

import com.aliyuncs.exceptions.ClientException;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.User;
import com.company.project.service.impl.UserServiceImpl;
import com.company.project.util.Md5;
import com.company.project.util.PageUtil;
import com.company.project.util.SendMessageController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.reflect.generics.scope.Scope;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by CodeGenerator on 2018/10/08.
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private UserServiceImpl userService;

    @Resource
    private SendMessageController sendMessageController;

    //前台登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public User login(@RequestBody User user) {
        user.setPwd(Md5.MD5Encode(user.getPwd()));
        User login = userService.login(user.getName(), user.getPwd());
        if (login != null){
            logger.info(user.getName()+"登录了 ");
        }
        return userService.login(user.getName(), user.getPwd());
    }

    /**
     * 前台修改密码
     * @param user
     * @return
     */
    @PostMapping("/UPCode")
    @ResponseBody
    public Result UPCode(@RequestBody User user){
        user.setPwd(Md5.MD5Encode(user.getPwd()));
        Boolean aBoolean = userService.upCode(user);
        return ResultGenerator.genSuccessResult(aBoolean);
    }

    /**
     * 后台修改密码
     * @param user
     * @return
     */
    @PostMapping("/manageUP")
    @ResponseBody
    public Result adminUP(@RequestBody User user){
        user.setPwd(Md5.MD5Encode(user.getPwd()));
        String s = userService.adminUP(user);
        return ResultGenerator.genSuccessResult(s);
    }
    //注册
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody(required = false) User user) {
        if (user == null) {
            return ResultGenerator.genFailResult("[/user/add] 请求参数错误");
        }
        user.setCreateTime(new Date());
        user.setPwd(Md5.MD5Encode(user.getPwd()));
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 根据id修改个人信息
     * @param
     * @return
     */
    @PostMapping("/UpUser")
    @ResponseBody
    public Result upUser(@RequestBody User user){
        Boolean aBoolean = userService.UPUser(user);
        return ResultGenerator.genSuccessResult(aBoolean);
    }

    //根据id查询个人信息
    @RequestMapping(value = "/selectMessage/{id}", method = RequestMethod.GET)
    public Result selectMessage(@PathVariable("id") Integer id) {
        User user = userService.selectMessage(id);
        return ResultGenerator.genSuccessResult(user);
    }

    //后台查询根据id查询权限
    @GetMapping(value = "/enter/{id}")
    @ResponseBody
    public List<Map<Object, Object>> enter(@PathVariable("id") Integer id) {
        List<Map<Object, Object>> enter = userService.enter(id);
        return enter;
    }

    //后台头部
    @PostMapping(value = "/register")
    @ResponseBody
    public List<User> register(@RequestBody(required = false) User user) {
        List<User> register = userService.register(user.getName(), user.getPwd());
        return register;
    }

    /**
     * 后台查询所有用户和用户角色
     * @param index
     * @return
     */
    @GetMapping("/selectAllUserRole/{index}")
    @ResponseBody
    public PageUtil<User> selectAllUserRole(@PathVariable(value = "index") Integer index) {
        PageUtil<User> userPageUtil = userService.selectAllUserRole(index);
        return userPageUtil;
    }

    /**
     * 修改用户信息和用户角色
     *
     * @param user
     * @return
     */
    @PostMapping("/updateAll")
    @ResponseBody
    public Result updateAll(@RequestBody User user) {
        Boolean aBoolean = userService.updateUser(user);
        return ResultGenerator.genSuccessResult(aBoolean);
    }

    /**
     * 后台修改用户状态
     * @return
     */
    @PostMapping("/UPState")
    @ResponseBody
    public Result UPState(@RequestBody User user){
        Boolean aBoolean = userService.UPState(user);
        return ResultGenerator.genSuccessResult(aBoolean);
    }
    /**
     * 删除用户角色
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @ResponseBody
    public Result delete(@PathVariable("id") Integer id) {
        Boolean aBoolean = userService.deleteAllUser(id);
        return ResultGenerator.genSuccessResult(aBoolean);
    }


    //注册
    @PostMapping("/add/user")
    public Boolean verifyPhone(@RequestBody User user){
       String pwd = Md5.MD5Encode(user.getPwd());
        if(pwd==null){
            return  false;
        }
        user.setPwd(pwd);
        return userService.addUser(user);
    }

    //验证手机号唯一
    @GetMapping("/verify/phone/{phone}")
    public Boolean verifyPhone(@PathVariable String phone){
        Boolean b =userService.verifyPhone(phone);
        if (b){
            return false;
        }
        return true;
    }

    //验证用户名唯一
    @GetMapping("/verify/name/{name}")
    public Boolean verifyName(@PathVariable String name){
        Boolean b =userService.verifyName(name);
        if (b){
            return false;
        }
        return true;
    }

    //验证码校验
    @GetMapping("/verify/auth/code/{phone}/{code}")
    public Result verifyAuthCode(@PathVariable String phone ,@PathVariable String code,HttpServletRequest httpServletRequest){
        if(phone!=null && code!=null && !("").equals(phone) && !("").equals(code)){
            String key = httpServletRequest.getSession().getAttribute(phone).toString();
            if(key==null){
                return ResultGenerator.getInternalServerErrot("验证码输入错误");
            }else {
                if ((code).equals(key)){
                    return ResultGenerator.genSuccessResult("验证码输入正确");
                }else{
                    return ResultGenerator.getInternalServerErrot("验证码输入错误");
                }
            }
        }
        return ResultGenerator.getInternalServerErrot("手机号或验证码不能为空");

    }

    //注册获取验证码
    @GetMapping("/get/auth/register/code/{phone}")
    public Result getAuthCodeRegister(@PathVariable String phone, HttpSession httpSession){
        String code =null;
        try {
            code = sendMessageController.getVerification(phone,"REGISTER");
        } catch (ClientException e) {
            e.printStackTrace();
            return ResultGenerator.getInternalServerErrot("验证码后台错误");
        }
        httpSession.setAttribute(phone,code);
        return ResultGenerator.genSuccessResult("验证码发送成功");
    }


    @PostMapping("/update")
    public Result update(User user) {
        userService.update(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        User user = userService.findById(id);
        return ResultGenerator.genSuccessResult(user);
    }

    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<User> list = userService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }
}
